package com.xxl.util;

import com.xxl.controll.EmailController;
import jakarta.annotation.Resource;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.Random;

/**
 * @author xxl
 * @date 2023/3/23
 */
@Component
@Slf4j
public class EmailUtil {


    /**
     *  发送邮件的对象
     */
    @Resource
    JavaMailSenderImpl sender;
    @Value("${emailAddress}")
    private String emailAddress;
    /**
     *  简单邮件
     */
    @Async
    public void simpleEmail(String email) {
        System.out.println("用${}取yml文件的配置="+emailAddress);
        //写邮件的主体
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        //邮件主题
        simpleMailMessage.setSubject("邮件注册");
        EmailController.verificationCode = ""+new Random().nextInt(99999);
        //邮件内容
//        simpleMailMessage.setText("注册码="+EmailController.verificationCode);
        simpleMailMessage.setText("""
                <p style='color: red;font-size: 30px'>注册码： """+EmailController.verificationCode+"</p>");
        //发给谁
        simpleMailMessage.setTo(email);
        //谁发出去
        simpleMailMessage.setFrom(emailAddress);
        //发送
        sender.send(simpleMailMessage);
    }
    /**
     *  复杂邮件
     */
    @Async
    public void complexEmail(String email)   {
        try {
            //创建复杂邮件
            MimeMessage mimeMessage = sender.createMimeMessage();
            //组装,构造带”true“开启多文件
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"UTF-8");
            //设置主题
            helper.setSubject("邮件注册");
            //设置内容
            EmailController.verificationCode = ""+new Random().nextInt(99999);
            helper.setText("<p style='color: #6cbe45;font-size: 30px'>验证码"+EmailController.verificationCode+"</p>",true);
            //携带附件
            helper.addAttachment("application.yml附件", new File("D:\\Program Files (x86)\\idea\\IDEAproject\\spring-boot-study\\demo11_mail\\target\\classes\\application.yml"));
            //发给谁
            helper.setTo(email);
            //谁发
            helper.setFrom(emailAddress);
            //发送
            sender.send(mimeMessage);
        } catch (MessagingException e) {
            log.error("没有流="+e.getMessage());
        }
    }
}
